package cn.shixiaoyu.demo.dao.implStu;

import cn.shixiaoyu.demo.dao.IStuDao;
import cn.shixiaoyu.demo.domain.Student;
import cn.shixiaoyu.demo.util.JdbcStuUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StuDaoImpl implements IStuDao {
    JdbcStuUtil jdbc =new JdbcStuUtil();
    Statement statement = jdbc.jdbcStatement();
    @Override
    public int addStu(Student stu) {
        try {
            int res = statement.executeUpdate("insert into student(username,password,age,sex,intro) value ('" + stu.getUsername() + "','" + stu.getPassword() + "'," + stu.getAge() + "," + stu.getSex() + ",'" + stu.getIntro() + "')");
            return res;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbc.closeJdbc(null);
        }
    }

    @Override
    public int editStu(Student stu) {
        try {
            int res = statement.executeUpdate("update student set username = '"+stu.getUsername()+"',password = '"+stu.getPassword()+"',age="+stu.getAge()+",sex="+stu.getSex()+",intro='"+stu.getIntro()+"' where id = "+stu.getId()+";");
            return res;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbc.closeJdbc(null);
        }
    }

    @Override
    public int deleteStu(Long id) {
        try {
            int res = statement.executeUpdate("delete from student where id = "+id+";");
            return res;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbc.closeJdbc(null);
        }
    }

    @Override
    public Student viewStu(Long id) {
        ResultSet res = null;
        try {
             res = statement.executeQuery("select * from student where id = "+id+";");
            if(res.next()){
                return new Student(res.getLong("id"),res.getString("username"),res.getString("password"),res.getInt("age"),res.getInt("sex"),res.getString("intro"));
            }
            return null;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbc.closeJdbc(res);
        }
    }

    @Override
    public List<Student> viewAllStu() {
        ResultSet res = null;
        List<Student> list = new ArrayList();
        try {
            res = statement.executeQuery("select * from student;");
            while(res.next()){
                 Student stu = new Student(res.getLong("id"),res.getString("username"),res.getString("password"),res.getInt("age"),res.getInt("sex"),res.getString("intro"));
                list.add(stu);

            }
            return list;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            jdbc.closeJdbc(res);
        }
    }
}
